package com.sc.security.service.impl;

import com.google.common.collect.Lists;
import com.google.common.collect.Sets;
import com.sc.security.beans.LogService;
import com.sc.security.common.RequestHolder;
import com.sc.security.dao.SysRoleUserMapper;
import com.sc.security.dao.SysUserMapper;
import com.sc.security.model.SysRoleUser;
import com.sc.security.model.SysUser;
import com.sc.security.service.RoleUserService;
import com.sc.security.utils.IpUtil;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;
import java.util.Set;

@Service
public class RoleUserServiceImpl implements RoleUserService {
    @Autowired
    private SysRoleUserMapper roleUserMapper;
    @Autowired
    private SysUserMapper userMapper;
    @Autowired
    private LogService logService;
    @Override
    public List<SysUser> getListByRoleId(Integer roleId) {
        List<Integer> idList = roleUserMapper.getUserIdListByRoleId(roleId);
        if(CollectionUtils.isEmpty(idList)){
            return Lists.newArrayList();
        }
        return  userMapper.selectByIdList(idList);
    }

    @Override
    public void changeRoleUsers(Integer roleId, List<Integer> userIdList) {
        List<Integer> originUserIdList = roleUserMapper.getUserIdListByRoleId(roleId);
        if (originUserIdList.size() == userIdList.size()) {
            Set<Integer> originUserIdSet = Sets.newHashSet(originUserIdList);
            Set<Integer> userIdSet = Sets.newHashSet(userIdList);
            originUserIdSet.removeAll(userIdSet);
            if (CollectionUtils.isEmpty(originUserIdSet)) {
                return;
            }
        }
        updateRoleUsers(roleId, userIdList);
        logService.saveRoleUser(roleId,originUserIdList,userIdList);
    }
    @Transactional
    public void updateRoleUsers(Integer roleId, List<Integer> userIdList) {
        roleUserMapper.deleteByRoleId(roleId);

        if (CollectionUtils.isEmpty(userIdList)) {
            return;
        }
        List<SysRoleUser> roleUserList = Lists.newArrayList();
        for (Integer userId : userIdList) {
            SysRoleUser roleUser = SysRoleUser.builder().roleId(roleId).userId(userId).operator(RequestHolder.getCurrentUser().getUsername())
                    .operateIp(IpUtil.getRemoteIp(RequestHolder.getCurrentRequest())).operateTime(new
                            Date()).build();
            roleUserList.add(roleUser);
        }
        roleUserMapper.batchInsert(roleUserList);
    }
}
